// KMS系统数据验证脚本
function validateKMSData() {
    console.log('开始验证KMS系统数据完整性...');
    
    const localStorageKeys = [
        'demo_keys',
        'demo_templates',
        'demo_keyRequests',
        'demo_keyDistributions',
        'demo_distributionConfig',
        'demo_backupHistory',
        'demo_forensicPersonnel',
        'demo_forensicLogs'
    ];
    
    let allDataValid = true;
    const validationResults = {};
    
    localStorageKeys.forEach(key => {
        try {
            const data = localStorage.getItem(key);
            validationResults[key] = {
                exists: !!data,
                isEmpty: !data || JSON.parse(data).length === 0,
                error: null
            };
            
            if (data) {
                const parsedData = JSON.parse(data);
                if (!Array.isArray(parsedData)) {
                    validationResults[key].error = '数据不是有效的数组';
                    allDataValid = false;
                } else {
                    console.log(`${key}: 包含 ${parsedData.length} 条记录`);
                }
            } else {
                validationResults[key].error = '数据不存在';
                allDataValid = false;
            }
        } catch (error) {
            validationResults[key].error = error.message;
            allDataValid = false;
            console.error(`验证 ${key} 时出错:`, error);
        }
    });
    
    // 验证关键数据关系
    try {
        const keys = JSON.parse(localStorage.getItem('demo_keys') || '[]');
        const templates = JSON.parse(localStorage.getItem('demo_templates') || '[]');
        
        // 验证密钥引用的模板是否存在
        keys.forEach(key => {
            if (key.templateId) {
                const templateExists = templates.some(t => t.id === key.templateId);
                if (!templateExists) {
                    console.error(`密钥 ${key.id} 引用了不存在的模板 ${key.templateId}`);
                    allDataValid = false;
                }
            }
        });
    } catch (error) {
        console.error('验证数据关系时出错:', error);
        allDataValid = false;
    }
    
    console.log('验证结果汇总:', validationResults);
    console.log('总体数据完整性:', allDataValid ? '通过' : '失败');
    
    return {
        allValid: allDataValid,
        results: validationResults
    };
}

// 导出函数以便在控制台调用
window.validateKMSData = validateKMSData;

// 如果直接运行此脚本，立即执行验证
if (typeof module === 'undefined') {
    validateKMSData();
}